package com.atguigu.tingshu.order.pattern.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.order.pattern.AbstractTradeStrategy;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: atguigu
 * @create: 2025-06-17 09:34
 */
@Component(SystemConstant.ORDER_ITEM_TYPE_ALBUM)
public class AlbumTrade extends AbstractTradeStrategy {


    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 对会员VIP进行结算
     * @param tradeVo
     * @return
     */
    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        Long userId = AuthContextHolder.getUserId();
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //1.初始化订单VO中价格、订单明细列表、订单减免明细列表
        //1.1 声明三个初始价格：原价、减免金额、订单金额
        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");
        //1.2 声明封装订单明细集合
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //1.3 声明封装订单减免明细集合
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();


        //3. 处理购买项目类型：专辑
        //3.1 远程调用用户服务，判断用户是否已购买过专辑，如果已买则响应已购买
        Long albumId = tradeVo.getItemId();
        Boolean flag = userFeignClient.isPaidAlbum(albumId).getData();
        if (flag) {
            throw new GuiguException(500, "用户已购买专辑");
        }

        //3.2 远程调用专辑服务，获取专辑价格以及相关折扣(普通、VIP折扣)
        AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
        Assert.notNull(albumInfo, "专辑{}不存在", albumId);
        BigDecimal price = albumInfo.getPrice();
        BigDecimal discount = albumInfo.getDiscount();
        BigDecimal vipDiscount = albumInfo.getVipDiscount();

        //3.3 远程调用用户服务，判断当前用户是否是会员
        Boolean isVIP = false;

        UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
        Assert.notNull(userInfoVo, "用户{}不存在", userId);
        if (userInfoVo.getIsVip().intValue() == 1 && userInfoVo.getVipExpireTime().after(new Date())) {
            isVIP = true;
        }

        //3.4 基于用户角色专辑折扣计算专辑价格(原价、订单价、减免价格)
        originalAmount = price;
        orderAmount = originalAmount;
        if (!isVIP && discount.doubleValue() != -1) {
            //专辑价格 普通用户折扣  订单价格=原价*折扣
            orderAmount =
                    originalAmount.multiply(discount).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
        }
        if (isVIP && vipDiscount.doubleValue() != -1) {
            //专辑价格 VIP会员折扣  订单价格=原价*折扣
            orderAmount =
                    originalAmount.multiply(vipDiscount).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
        }
        //计算专辑价格减免金额 = 原价-订单价格
        derateAmount = originalAmount.subtract(orderAmount);
        //3.5 将专辑信息作为订单明细，封装成订单明细VO对象，加入到订单明细列表
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(albumId);
        orderDetailVo.setItemName("专辑：" + albumInfo.getAlbumTitle());
        orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
        orderDetailVo.setItemPrice(originalAmount);
        orderDetailVoList.add(orderDetailVo);

        //3.6 如有优惠金额，封装订单减免vo对象，加入到订单减免列表
        if (originalAmount.compareTo(orderAmount) == 1) {
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            orderDerateVo.setDerateAmount(derateAmount);
            orderDerateVo.setRemarks("专辑折扣减免：" + derateAmount);
            orderDerateVoList.add(orderDerateVo);
        }

        //5.封装订单VO信息共有的信息，价格赋值、商品明细列表赋值、订单减免明细列表赋值、流水号机制、签名机制
        //5.1 封装第一类信息：三个价格（原价、订单价、减免价）
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);

        //5.2 封装第二类信息：商品明细列表、优惠列表
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        //5.3 封装第三类信息：购买项目类型、流水号机制（本次订单流水号）、签名机制（时间戳+签名值）
        orderInfoVo.setItemType(tradeVo.getItemType());
        //5.3.1 流水号机制第一步：生成本次订单流水号，解决回退、重复点击提交造成订单重复提交问题
        this.generateTradeNo(orderInfoVo);
        //5.3.2 签名机制第一步：生成签名值
        this.generateSign(orderInfoVo);
        return orderInfoVo;
    }
}
